package com.kehao.leetcode.jzoffer;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/23 14:24
 */
public class JZSolution022 {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {
        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode detectCycle(ListNode head) {
        if(head==null) return null;
        if(head.next == null) return null;
        if(head.next == head) return head;
        if(head.next.next == head) return head;

        ListNode fast = head.next.next;
        ListNode slow = head.next;
        while (fast!=slow){
            slow = slow.next;
            try {
                fast = fast.next.next;
            }catch (NullPointerException e){
                return null;
            }
        }

        fast = head;
        while (fast!=slow){
            fast = fast.next;
            slow = slow.next;
        }

        return fast;
    }
}
